package com.demo.paypalmanagement.service;

import com.demo.paypalmanagement.common.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CaptchaService {
    private final StringRedisTemplate redisTemplate;

    public CaptchaService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 保存验证码到 Redis
    public void saveCaptcha(String businessType, String email, String captcha) {
        String key = generateKey(businessType, email);
        redisTemplate.opsForValue().set(key, captcha, RedisConstants.CAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS); // 有效期1分钟
    }

    // 验证验证码
    public boolean validateCaptcha(String businessType, String email, String captcha) {
        String key = generateKey(businessType, email);
        String storedCaptcha = redisTemplate.opsForValue().get(key);
        return storedCaptcha != null && storedCaptcha.equals(captcha);
    }

    // 生成 Redis key
    private String generateKey(String businessType, String email) {
        return businessType  + email;
    }
}
